﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
using System.Windows.Forms;
using EzPos.GUIs.Forms;
using EzPos.Model.Common;
using EzPos.Model.Table;
using EzPos.Properties;
using EzPos.Service;
using EzPos.Service.Common;
using EzPos.Service.Table;
using EzPos.Service.User;
using EzPos.Utility;

namespace EzPos.GUIs.Controls
{
    public partial class CtrlTable : UserControl
    {
        private CommonService _commonService;
        private BindingList<Table> _tableList;
        private UserService _userService;
        private TableService _tableService;

        public CtrlTable()
        {
            InitializeComponent();
        }

        public UserService UserService
        {
            set { _userService = value; }
        }

        public TableService TableService
        {
            set { _tableService = value; }
        }

        public CommonService CommonService
        {
            set { _commonService = value; }
        }

        private void BtnNewClick(object sender, EventArgs e)
        {
            if (!UserService.AllowToPerform(Resources.PermissionAddTable))
            {
                const string briefMsg = "អំពី​សិទ្ឋិ​ប្រើ​ប្រាស់";
                var detailMsg = Resources.MsgUserPermissionDeny;
                using (var frmMessageBox = new FrmExtendedMessageBox())
                {
                    frmMessageBox.BriefMsgStr = briefMsg;
                    frmMessageBox.DetailMsgStr = detailMsg;
                    frmMessageBox.IsCanceledOnly = true;
                    frmMessageBox.ShowDialog(this);
                    return;
                }
            }

            TableManagement(Resources.OperationRequestInsert);
        }

        private void BtnDeleteClick(object sender, EventArgs e)
        {
            string briefMsg, detailMsg;

            if (!UserService.AllowToPerform(Resources.PermissionDeleteTable))
            {
                briefMsg = "អំពី​សិទ្ឋិ​ប្រើ​ប្រាស់";
                detailMsg = Resources.MsgUserPermissionDeny;
                using (var frmMessageBox = new FrmExtendedMessageBox())
                {
                    frmMessageBox.BriefMsgStr = briefMsg;
                    frmMessageBox.DetailMsgStr = detailMsg;
                    frmMessageBox.IsCanceledOnly = true;
                    frmMessageBox.ShowDialog(this);
                    return;
                }
            }

            briefMsg = "អំពីការលុប";
            detailMsg = Resources.MsgOperationRequestDelete + "\n" +
                        dgvTable.CurrentRow.Cells["TableName"].Value + " ?";
            using (var frmMessageBox = new FrmExtendedMessageBox())
            {
                frmMessageBox.BriefMsgStr = briefMsg;
                frmMessageBox.DetailMsgStr = detailMsg;
                if (frmMessageBox.ShowDialog(this) != DialogResult.OK)
                    return;
            }

            try
            {
                _tableService.TableManagement(
                    _tableList[dgvTable.CurrentRow.Index],
                    Resources.OperationRequestDelete);

                _tableList.RemoveAt(dgvTable.CurrentRow.Index);
                dgvTable.Refresh();
                UpdateResultInfo();
                EnableActionButton();
            }
            catch (Exception exception)
            {
                FrmExtendedMessageBox.UnknownErrorMessage(
                    Resources.MsgCaptionUnknownError,
                    exception.Message);
            }
        }

        private void CtrlUser_Load(object sender, EventArgs e)
        {
            if (_userService == null)
                _userService = ServiceFactory.GenerateServiceInstance().GenerateUserService();

            if (_commonService == null)
                _commonService = ServiceFactory.GenerateServiceInstance().GenerateCommonService();

            if (_tableService == null)
                _tableService = ServiceFactory.GenerateServiceInstance().GenerateTableService();

            //if (!UserService.AllowToPerform(Resources.PermissionViewUserResultInfo))            
            //    lblResultInfo.Visible = false;
            
            //if (!UserService.AllowToPerform(Resources.PermissionViewUserResultInfo))            
            //    lblResultInfo.Visible = false;
            
            InitializeUserList();

            ThreadStart threadStart = UpdateControlContent;
            var thread = new Thread(threadStart) {IsBackground = true};
            thread.Start();

            IListToBindingList(_tableService.GetTables());
            dgvTable.Refresh();
        }

        private void DgvUserDataError(object sender, DataGridViewDataErrorEventArgs e)
        {
            FrmExtendedMessageBox.UnknownErrorMessage(
                Resources.MsgCaptionUnknownError,
                e.Exception.Message);
        }

        private void DgvUserCellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (!UserService.AllowToPerform(Resources.PermissionEditTable))
            {
                const string briefMsg = "អំពី​សិទ្ឋិ​ប្រើ​ប្រាស់";
                var detailMsg = Resources.MsgUserPermissionDeny;
                using (var frmMessageBox = new FrmExtendedMessageBox())
                {
                    frmMessageBox.BriefMsgStr = briefMsg;
                    frmMessageBox.DetailMsgStr = detailMsg;
                    frmMessageBox.IsCanceledOnly = true;
                    frmMessageBox.ShowDialog(this);
                    return;
                }
            }

            TableManagement(Resources.OperationRequestUpdate);
        }

        private void InitializeUserList()
        {
            try
            {
                if (_tableList == null)
                    _tableList = new BindingList<Table>();

                dgvTable.DataSource = _tableList;
                dgvTable.Columns["TableName"].DisplayIndex = 0;
                dgvTable.Columns["BusyStatus"].DisplayIndex = 1;
                dgvTable.Columns["SaleOrderNumber"].DisplayIndex = 2;
            }
            catch (Exception exception)
            {
                FrmExtendedMessageBox.UnknownErrorMessage(
                    Resources.MsgCaptionUnknownError,
                    exception.Message);
            }
        }

        private void IListToBindingList(IList tableList)
        {
            if (tableList == null)
                throw new ArgumentNullException("tableList", string.Empty);

            if (_tableList == null)
                return;

            _tableList.Clear();
            foreach (Table table in tableList)
                _tableList.Add(table);

            UpdateResultInfo();
            EnableActionButton();
        }

        private void EnableActionButton()
        {
            btnDelete.Enabled = _tableList.Count != 0;

            SetFocusToUserList();
        }

        private void SetFocusToUserList()
        {
            if (dgvTable.CanFocus)
                dgvTable.Focus();
        }

        private void TableManagement(IEquatable<string> operationRequest)
        {
            using (var frmTable = new FrmTable())
            {
                if (operationRequest.Equals(Resources.OperationRequestUpdate))
                {
                    if (dgvTable.CurrentRow != null)
                        frmTable.Table = _tableList[dgvTable.CurrentRow.Index];
                }

                if (frmTable.ShowDialog(this) != DialogResult.OK)
                    return;
                
                try
                {
                    if ((operationRequest.Equals(Resources.OperationRequestInsert)))
                        _tableList.Add(frmTable.Table);
                    dgvTable.Refresh();
                    UpdateResultInfo();
                    EnableActionButton();
                }
                catch (Exception exception)
                {
                    FrmExtendedMessageBox.UnknownErrorMessage(
                        Resources.MsgCaptionUnknownError,
                        exception.Message);
                }                
            }
        }

        private void UpdateResultInfo()
        {
            var resultNum = 0;
            if (_tableList != null)
                resultNum = _tableList.Count;

            var strResultInfo = string.Format(
                "ការសែ្វងរករបស់អ្នកផ្តល់លទ្ឋផលចំនួន {0}",
                resultNum.ToString("N0", AppContext.CultureInfo));
            lblResultInfo.Text = strResultInfo;
        }

        private void BtnResetClick(object sender, EventArgs e)
        {
            txtTableName.Text = string.Empty;
            cmbBusyStatus.SelectedIndex = -1;
            BtnSearchClick(sender, e);
        }

        private void BtnSearchClick(object sender, EventArgs e)
        {
            var searchCriteria = new List<string>();
            if (StringHelper.Length(txtTableName.Text) != 0)
                searchCriteria.Add("TableName LIKE '%" + txtTableName.Text + "%'");

            if (cmbBusyStatus.SelectedIndex != -1)
            {
                searchCriteria.Add("SaleOrderId" + 
                    (cmbBusyStatus.Text.Equals("Yes") ?
                    " <> 0" :
                    " = 0"));
            }

            IListToBindingList(
                _tableService.GetTables(searchCriteria));
            dgvTable.Refresh();
        }

        private void UpdateControlContent()
        {
            SafeCrossCallBackDelegate safeCrossCallBackDelegate = null;
            if (cmbBusyStatus.InvokeRequired)
                safeCrossCallBackDelegate = UpdateControlContent;

            if (cmbBusyStatus.InvokeRequired)
                Invoke(safeCrossCallBackDelegate);
            else
            {
                var searchCriteria = new List<string> {"ParameterTypeId IN (70)"};

                var objList = _commonService.GetAppParameters(searchCriteria);

                _commonService.PopAppParamExtendedCombobox(
                    ref cmbBusyStatus, 
                    objList, 
                    int.Parse(Resources.AppParamBusyStatus, AppContext.CultureInfo), 
                    false);
            }
        }

        private void BtnNewMouseEnter(object sender, EventArgs e)
        {
            btnNew.BackgroundImage = Resources.background_9;
        }

        private void BtnDeleteMouseEnter(object sender, EventArgs e)
        {
            btnDelete.BackgroundImage = Resources.background_9;
        }

        private void BtnDeleteMouseLeave(object sender, EventArgs e)
        {
            btnDelete.BackgroundImage = null;
        }

        private void BtnNewMouseLeave(object sender, EventArgs e)
        {
            btnNew.BackgroundImage = null;
        }

        #region Nested type: SafeCrossCallBackDelegate

        private delegate void SafeCrossCallBackDelegate();

        #endregion
    }
}